import Sock from 'sockjs-client'
import Stomp from 'webstomp-client'

class SocketClient {
  client = null
  subscriptions = []
  options = {
    debug: process.env.NODE_ENV !== 'production'
  }
  retryTimes = 5

  connect (subscriptions) {
    this.client = Stomp.over(new Sock('/chat'), this.options)

    const connectedHandler = () => {
      subscriptions.forEach(item => {
        const subscription = this.client.subscribe(item.destination, message => {
          item.handler(message.body)
        })

        this.subscriptions.push(subscription)
      })
    }

    const errorHandler = (error) => {
      if (this.options.debug) {
        console.error(error)
      }

      if (error.type === 'close') {
        if (this.retryTimes < 1) {
          window.location.reload()
        }

        setTimeout(() => {
          this.disconnect()
          this.connect(subscriptions)
          this.retryTimes--
        }, 100)
      }
    }

    this.client.connect({}, connectedHandler, errorHandler)
  }

  disconnect(subscriptions = this.subscriptions) {
    const item = subscriptions.pop()
    if (item) {
      item.unsubscribe()
      this.disconnect(subscriptions)
    }
  }
}

export default new SocketClient()
